// 获取应用实例
const app = getApp()

Page({
    data: {
        bom_index: 0,
        bom_index2: 0,
        is_show_choose_pro: false,
        buyer_list: [],
        material_type_list: [],
        supplier_list: [],
        supplier_total: 0,
        supplier_now_page: 0,
        supplier_keywords: '',
        selectUnit: {},
        limit: 50,
        sel_text: {
            buyer_text: '',
            type_text: '',
            supply_text: '',
            choose_cate_name: ''
        },
        bom_list: [],
        type_list: [
            { id: 1, name: '春' },
            { id: 2, name: '夏' },
            { id: 3, name: '秋' },
            { id: 4, name: '冬' },
            { id: 5, name: '通用' },
        ],
        is_shade_screen: false,
        is_show_choose_supplier: false,
        sel_table_head: [
            { name: '物料名称', field: 'material_name', is_checked: 1, width: 350 },
            { name: '供应商', field: 'supply_name', is_checked: 0, width: 200 },
            { name: '颜色', field: 'material_color', is_checked: 0, width: 120 },
            { name: '采购数量', field: 'confirm_num', is_checked: 1, width: 200 },
            { name: '单价', field: 'price', is_checked: 1, width: 150 },
            { name: '用途', field: 'material_use', is_checked: 1, width: 200 },
            { name: '成品简码', field: 'template_no', is_checked: 1, width: 200 },
            { name: '单件用量', field: 'single_piece', is_checked: 1, width: 200 },
            { name: '预计交期', field: 'dead_line', is_checked: 1, width: 200 },
            { name: '备注', field: 'remark', is_checked: 1, width: 200 },
        ],
        purchase_id: 0,
        edit_data: null,
        formData: {
            purchase_time: '',
            purchase_name: '南昌岳歌',
            first_order: true,
            buyer_id: 0,
            type: 0,
            supply_id: 0,
            sg_purchase_sn: '',
        },
        // formData: {
        //   purchase_time: '2023-09-05',
        //   purchase_name: '南昌岳歌',
        //   first_order: true,
        //   buyer_id: 4,
        //   type: 1,
        //   supply_id: 2148,
        //   sg_purchase_sn: '',
        // },
        is_close_phot: false,
        sel_season_arr: [0, 0],
        materials: [
            {
                // "material_name":"测试面料张叶",
                // "material_type":2,
                // "unit":'米',
                // "check_unit":'米',
                // "price":'1',
                // "check_price":'1',
                // "unit_rate":'1',
                // "material_attr":'100%碳纤维',
                // "cloth_width":'100cm',
                // "gram_weight":'100m',
                // "no_use_rate":'缩率',
                // "material_use":'用途',
                // "single_piece":'单耗',
                // "material_grade":'面料等级',
                // "grade_category":'等级分类',
                // "pocketing":'口袋布',
                // "remark":'备注',
                // "template_no":'23Y23',
                // "sku_list":[
                //   {
                //     "color":"红色",
                //     "confirm_num":"100",
                //     // "template_no":"23Y123",
                //     "dead_line":"2023-09-05"
                //   }
                // ]
            },
        ],
        date: '',
        show: false,
        prop_list: [
            { "value": 1, "label": "首单" },
            { "value": 0, "label": "补单" },
            { "value": 2, "label": "加单" },
            { "value": 3, "label": "备料" }
        ],
        season_data: [
            {
                "label": "初春",
                "children": [
                    {
                        "label": "初春1",
                    },
                    {
                        "label": "初春2",
                    },
                ],
            },
            {
                "label": "正春",
                "children": [
                    {
                        "label": "正春1",
                    },
                    {
                        "label": "正春2",
                    },
                ],
            },
            {
                "label": "初夏",
                "children": [{
                    "label": "初夏1",
                },
                {
                    "label": "初夏2",
                },],
            },
            {
                "label": "盛夏",
                "children": [
                    {
                        "label": "盛夏1",
                    },
                    {
                        "label": "盛夏2",
                    },
                ],
            },
            {
                "label": "初秋",
                "children": [
                    {
                        "label": "初秋1",
                    },
                    {
                        "label": "初秋2",
                    },
                ],
            },
            {
                "label": "深秋",
                "children": [
                    {
                        "label": "深秋1",
                    },
                    {
                        "label": "深秋2",
                    },

                ],
            },
            {
                "label": "初冬",
                "children": [
                    {
                        "label": "初冬1",
                    },
                    {
                        "label": "初冬2",
                    },
                ],
            },
            {
                "label": "深冬",
                "children": [
                    {
                        "label": "深冬1",
                    },
                    {
                        "label": "深冬2",
                    },
                ],
            },
            {
                "label": "通季",
                "children": [
                    {
                        "label": "通季",
                    },
                ],
            }
        ],
        season_show: [],
        season_all_data: [],
        cate_show_data: [],
        cate_all_data: [],
        sel_category_arr: [],
        choose_cate_id_arr: [],
        choose_cate_index_arr: [],
        sel_cate_arr: [],
        fileList: [],
        web_data: '',
    },
    // 获取上传标识
    get_web_config: function () {
        // 发起请求
        var result = app.request_api('admin/index/index', {}, true, 'GET');
        result.then(res => {
            console.log(res)
            this.setData({
                web_data: res
            });
        });
    },
    yearValueChange: function (e) {
        var year = e.detail.value;
        this.setData({
            [`formData.year`]: year,
        })
    },
    afterRead(event) {
        console.log('eventeventevent', event)
        let { index } = event.currentTarget.dataset
        var __this = this;
        const { file } = event.detail;
        console.log('event.detail', event.detail)
        const fileList = this.data.materials[index].fileList || [];

        file.forEach((v, k) => {
            fileList.push({ ...v });
        })

        console.log(fileList)
        var setname = `materials[${index}].fileList`;
        this.setData({ [setname]: fileList });
    },
    afterRead2(event) {
        let { index } = event.currentTarget.dataset
        var __this = this;
        const { file } = event.detail;
        const fileList = this.data.materials[index].fileList2 || [];
        fileList.push({ ...file });
        console.log(fileList)
        var setname = `materials[${index}].fileList2`;
        this.setData({ [setname]: fileList });
    },
    get_caigou_user() {

        var result = app.request_api('api/pro.User/getUserInfo', {
            select: true,
            limit: 9999,
        }, false);
        result.then(res => {
            let index = res.group_name_arr.findIndex(v => v == '采购')
            if (index != -1) {
                var buyer_list = this.data.buyer_list
                let buyer_index = buyer_list.findIndex(v => v.id == res.id)
                this.buyerChange({ detail: { value: buyer_index } });
                this.setData({
                    [`formData.buyer_id`]: res.id
                })
            }
        })
    },
    // 获取时间分类
    get_season_show: function () {
        // 发起请求
        var res = this.data.season_data
        var result = app.request_api('admin/GoodsTimeCategory/getTreeAll', {
            is_mini: 1
        }, false, 'GET');
        result.then(res => {
            this.setData({
                season_show: [res, res[0].children, res[0].children[0].children],
                season_all_data: res
            });
        });
        // this.setData ({
        //     season_show: [res, res[0].children],
        // });
    },
    // 风格分类值变化时
    seasonValueChange: function (e) {
        // console.log(e);
        var season_show = this.data.season_show;
        var choose_style_index_arr = e.detail.value;
        var choose_style_name = season_show[0][choose_style_index_arr[0]].label + '/' + season_show[1][choose_style_index_arr[1]].label + '/' + season_show[2][choose_style_index_arr[2]].label;

        this.setData({
            [`formData.year`]: season_show[0][choose_style_index_arr[0]].label,
            [`formData.season_one`]: season_show[1][choose_style_index_arr[1]].label,
            [`formData.season_two`]: season_show[2][choose_style_index_arr[2]].label,
            choose_style_id_arr: [season_show[0][choose_style_index_arr[0]].id, season_show[1][choose_style_index_arr[1]].id, season_show[2][choose_style_index_arr[2]].id],
            choose_style_index_arr: choose_style_index_arr,
            [`sel_text.choose_season_name`]: choose_style_name
        });
    },

    onDisplay() {
        this.setData({ show: true });
    },
    onClose() {
        this.setData({ show: false });
    },
    formatDate(date) {
        date = new Date(date);
        return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
    },
    onConfirm(event) {
        this.setData({
            show: false,
            date: this.formatDate(event.detail),
        });
    },


    onLoad(options) {
        const currentYear = new Date().getFullYear();
        this.setData({
            [`formData.year`]: currentYear.toString()
        });
        this.get_web_config();
        this.get_season_show();
        this.get_category_data()
        wx.setNavigationBarTitle({
            title: '快捷采购'
        });
        // 如果是修改
        if (options.purchase_id != undefined) {
            this.setData({
                purchase_id: options.purchase_id
            });
            wx.setNavigationBarTitle({
                title: '修改采购单'
            });
        }
        // 获取数据
        this.get_data_all();
    },

    get_category_data: function () {
        // 发起请求
        var result = app.request_api('admin/GoodsCategory/getTreeAll', {
            is_mini: 1
        }, false, 'GET');
        result.then(res => {
            this.setData({
                cate_show_data: [res, res[0].children, res[0].children[0].children],
                cate_all_data: res
            });
        });
    },

    // 分类值变化时
    CateValueChange: function (e) {
        // console.log(e);
        var cate_show_data = this.data.cate_show_data;
        var choose_cate_index_arr = e.detail.value;
        console.log(cate_show_data[0])
        var choose_cate_name = cate_show_data[0][choose_cate_index_arr[0]].category_name + '/' + cate_show_data[1][choose_cate_index_arr[1]].category_name + '/' + cate_show_data[2][choose_cate_index_arr[2]].category_name;
        this.setData({
            choose_cate_id_arr: [cate_show_data[0][choose_cate_index_arr[0]].id, cate_show_data[1][choose_cate_index_arr[1]].id, cate_show_data[2][choose_cate_index_arr[2]].id],
            choose_cate_index_arr: choose_cate_index_arr,
            [`sel_text.choose_cate_name`]: choose_cate_name
        });
    },

    // 风格分类列变化时
    seasonColumnChange: function (e) {
        // console.log(e);
        var season_all_data = this.data.season_all_data;
        var season_show = this.data.season_show;
        var sel_season_arr = this.data.sel_season_arr;
        var index = e.detail.value;
        if (e.detail.column == 0) {
            // 一级分类改变时
            console.log('一', season_all_data[index].children)
            this.data.season_show[1] = season_all_data[index].children;
            this.data.season_show[2] = season_all_data[index].children[0].children;
            sel_season_arr = [index, 0, 0];
        }
        if (e.detail.column == 1) {
            // 二级分类改变时
            this.data.season_show[2] = season_show[1][index].children;
            sel_season_arr[1] = index;
            sel_season_arr[2] = 0;
        }
        if (e.detail.column == 2) {
            // 二级分类改变时
            sel_season_arr[2] = index;
        }
        // 重新渲染
        this.setData({
            season_show: this.data.season_show,
            sel_season_arr: sel_season_arr
        });
    },

    // 分类列变化时
    CateColumnChange: function (e) {
        // console.log(e);
        var cate_all_data = this.data.cate_all_data;
        var cate_show_data = this.data.cate_show_data;
        var sel_cate_arr = this.data.sel_cate_arr;
        var index = e.detail.value;
        if (e.detail.column == 0) {
            // 一级分类改变时
            this.data.cate_show_data[1] = cate_all_data[index].children;
            this.data.cate_show_data[2] = cate_all_data[index].children[0].children;
            sel_cate_arr = [index, 0, 0];
        }
        if (e.detail.column == 1) {
            // 二级分类改变时
            this.data.cate_show_data[2] = cate_show_data[1][index].children;
            sel_cate_arr[1] = index;
            sel_cate_arr[2] = 0;
        }
        if (e.detail.column == 2) {
            // 三级分类改变时
            sel_cate_arr[2] = index;
        }
        // 重新渲染
        this.setData({
            cate_show_data: this.data.cate_show_data,
            sel_cate_arr: sel_cate_arr
        });
    },

    // 获取采购员
    get_buyer_list: function () {
        // 发起请求
        var result = app.request_api('admin/auth.admin/index', {
            select: true,
            limit: 9999,
            group_id: 7
        }, false);
        result.then(res => {
            this.setData({
                buyer_list: res.list
            });
        });
        // 返回
        return result;
    },
    // 输入生产数量时
    selInputChange: function (e) {
        var index = e.currentTarget.dataset.index;
        var index2 = e.currentTarget.dataset.index2;
        var field = e.currentTarget.dataset.field;
        var materials = this.data.materials
        materials[index]['sku_list'][index2][field] = e.detail.value;
        this.setData({
            materials,
        })
    },
    // 选择颜色
    ChooseColor: function (events) {
        var __this = this;
        let { index } = events.currentTarget.dataset
        // 打开选择颜色页面
        wx.navigateTo({
            url: '/pages/choose_color_purchase/choose_color_purchase',
            events: {
                // 当选择完成时
                changeData: function (data) {
                    data.forEach(function (v, k) {

                    })
                    const dynamicPropertyName = `materials[${index}].sku_list`;

                    __this.setData({
                        [dynamicPropertyName]: data
                    });
                }
            },
            success: function (res) {
                // 向被打开页面传送数据
                res.eventChannel.emit('acceptDataFromOpenerPage', {
                    sel_list: __this.data.materials[index].sku_list || []
                });
            }
        });
    },
    material_info_input: function (e) {
        let { field, index } = e.currentTarget.dataset
        let { value } = e.detail;
        var materials = this.data.materials

        materials[index][field] = value;
        if (field == 'price' && materials[index].unit_rate > 0) {
            materials[index].check_price = value * materials[index].unit_rate;
        }
        if (field == 'template_no') {
            let search = [];

            materials[index].total_bom_id = 0;
            materials[index].pro_list = [];
            materials[index].pro_list_ = [];
            materials[index].bom_id = [];
            materials[index].totalbom_bom_list = [];
            search.push({ operator: "=", val: value, field: "template_no" })
            var res = app.request_api("/admin/Template/index", { search });
            res.then((res) => {
                materials[index].fileList = [];
                materials[index].is_close_phot = false;
                this.setData({
                    materials,
                    is_close_phot: false,
                })
                if (res.list[0] !== undefined) {
                    let { template_id } = res.list[0];
                    this.getTotalBom(template_id, index);
                    var template_images = res.list[0].template_images
                    if (template_images !== undefined && Array.isArray(template_images) && template_images.length > 0) {
                        let fileList = [];
                        template_images.forEach((v, k) => {
                            fileList.push({
                                "url": v, "thumb": v, "fileType": "image", "value": v
                            })
                        })
                        materials[index].fileList = fileList;

                        materials[index].template_pro_cost = res.list[0].real_template_cost;
                        materials[index].template_retail_price = res.list[0].sale_price;
                        materials[index].is_close_phot = true;
                        this.setData({
                            materials,
                        })
                    }
                }
            })
        }
        this.setData({
            materials
        })
    },
    getTotalBom(template_id, index) {

        let search = []
        search.push({ field: "template.template_id", operator: "=", val: template_id })

        var res = app.request_api("/admin/TotalBom/index", { search, select: true });
        res.then((res) => {
            let new_list = []
            for (var k in res.list) {
                new_list.push(res.list[k])
            }

            let materials = this.data.materials;
            materials[index].pro_list = new_list
            materials[index].pro_list_ = res.list
            this.setData({
                materials
            })
        })

    },
    // 生产批次改变时
    proChange: function (e) {
        let materials = this.data.materials
        let { index } = e.currentTarget.dataset
        materials[index].total_bom_id = this.data.materials[index].pro_list[parseInt(e.detail.value)].total_bom_id;
        materials[index].totalbom_bom_list = this.data.materials[index].pro_list[parseInt(e.detail.value)].totalBomDetail;
        this.setData({
            materials,
        })
    },
    tap_add: function (e) {
        let { index, val } = e.currentTarget.dataset
        var materials = this.data.materials
        if (val == '-1') {
            materials.splice(index, 1)
        } else if (val == '1') {
            let material = JSON.parse(JSON.stringify(materials[index]));
            materials.push(material)
        } else {
            materials.push({})
        }

        this.setData({
            materials
        })
    },
    // 获取采购员
    get_buyer_list: function () {
        // 发起请求
        var result = app.request_api('admin/auth.admin/index', {
            select: true,
            limit: 9999,
            group_id: 7
        }, false);
        result.then(res => {
            this.setData({
                buyer_list: res.list
            });
            if (this.data.purchase_id == 0) {
                this.get_caigou_user();
            }

        });
        // 返回
        return result;
    },
    // 获取面料类型
    get_MaterialCategory_list: function () {
        // 发起请求
        var result = app.request_api('admin/MaterialCategory/index', {
            select: true,
            limit: 9999,
            group_id: 7
        }, false);
        result.then(res => {
            var newlist = [];
            res.list.forEach(function (v, k) {
                newlist[v.id] = v;
            })
            this.setData({
                material_type_list: res.list,
                material_type_list_new: newlist
            });
        });
        // 返回
        return result;
    },


    // 获取供应商
    get_supplier_list: function (is_search = 0) {
        var __this = this;
        // 验证
        if ((this.data.supplier_list.length >= this.data.supplier_total) && this.data.supplier_now_page > 0) {
            return false;
        }
        // 发起请求
        var result = app.request_api('admin/Supply/index', {
            page: __this.data.supplier_now_page + 1,
            quick_search: __this.data.supplier_keywords,
            limit: __this.data.limit,
            select:true
        }, false);
        result.then(res => {
            if (is_search == 1) {
                __this.setData({
                    supplier_list: [],
                    supplier_now_page: 0,
                    supplier_total: 0
                })
            }
            __this.setData({
                supplier_list: __this.data.supplier_list.concat(res.list),
                supplier_now_page: this.data.supplier_now_page + 1,
                supplier_total: res.total
            })
        });
        // 返回
        return result;
    },

    // 输入框改变
    formInputChange(e) {
        const { field } = e.currentTarget.dataset
        this.setData({
            [`formData.${field}`]: e.detail.value.trim()
        });
    },

    // 是否是首单
    firstOrderChange: function (e) {
        var first_order = false;
        if (e.detail.value) {
            first_order = true;
        }
        this.setData({
            [`formData.first_order`]: first_order
        })
    },

    // 采购时间
    bindDateChange: function (e) {
        this.setData({
            [`formData.purchase_time`]: e.detail.value
        })
    },
    propChange: function (e) {
        this.setData({
            [`formData.first_order`]: this.data.prop_list[e.detail.value].value,
        })
    },
    // 采购员改变时
    buyerChange: function (e) {

        this.setData({
            [`formData.buyer_id`]: this.data.buyer_list[parseInt(e.detail.value)].id,
            [`sel_text.buyer_text`]: this.data.buyer_list[parseInt(e.detail.value)].realname
        })
    },
    materialTypeChange: function (e) {
        let { index } = e.currentTarget.dataset
        var bianl = `materials[${index}].material_type`;
        this.setData({
            [bianl]: this.data.material_type_list[parseInt(e.detail.value)].id,
        })
    },
    // 订单属性改变时
    typeChange: function (e) {
        this.setData({
            [`formData.type`]: this.data.type_list[parseInt(e.detail.value)].id,
            [`sel_text.type_text`]: this.data.type_list[parseInt(e.detail.value)].name
        })
    },
    buildTemplateNo: function (e) {
        var __this = this;
        let index = e.currentTarget.dataset.index
        var req_param = this.data.formData;
        req_param.category_ids = this.data.choose_cate_id_arr;
        req_param.time_category_ids = this.data.choose_style_id_arr;
        var bianl = `materials[${index}].template_no`;

        var result = app.request_api('admin/Template/buildTemplateNo', req_param, false);
        result.then(res => {
            console.log(res)
            __this.setData({
                [bianl]: res.template_no
            })
        });
    },
    // 选择供应商
    choose_supplier: function (e) {
        // 清空已选择的物料
        if (this.data.supplier_list[parseInt(e.currentTarget.dataset.index)].id != this.data.formData.supply_id) {
            this.setData({
                bom_list: [],
            })
        }
        // 验证是否选择的是否和之前一样
        this.setData({
            [`formData.supply_id`]: this.data.supplier_list[parseInt(e.currentTarget.dataset.index)].id,
            [`sel_text.supply_text`]: this.data.supplier_list[parseInt(e.currentTarget.dataset.index)].SupplyNa
        });
        this.close_supplier_choose();
    },

    // 选择bom
    choose_bom: function (e) {
        // 清空已选择的物料
        // if (this.data.supplier_list[parseInt(e.currentTarget.dataset.index)].id != this.data.formData.supply_id) {
        //     this.setData({
        //         bom_list: [],
        //     })
        // }
        // 验证是否选择的是否和之前一样
        let materials = this.data.materials;
        let bom_index = this.data.bom_index
        let bom_index2 = this.data.bom_index2
        materials[bom_index].sku_list[bom_index2].bom_id = {
            total_bom_detail_id: this.data.materials[bom_index].totalbom_bom_list[parseInt(e.currentTarget.dataset.index)].total_bom_detail_id,
            bom_option_id: this.data.materials[bom_index].totalbom_bom_list[parseInt(e.currentTarget.dataset.index)].bom_option_id,
            name: this.data.materials[bom_index].totalbom_bom_list[parseInt(e.currentTarget.dataset.index)].bom_name
        }
        this.setData({
            materials
        });
        this.close_supplier_choose();
    },

    // 打开选择
    open_supplier_choose: function () {
        this.setData({
            is_shade_screen: true,
            is_show_choose_supplier: true
        })
    },

    // 关闭
    close_supplier_choose: function (e) {
        this.setData({
            is_shade_screen: false,
            is_show_choose_supplier: false,
            is_show_choose_pro: false,
        })
    },

    // 关闭
    close_pro_choose: function (e) {
        this.setData({
            is_shade_screen: false,
            is_show_choose_supplier: false
        })
    },

    // 搜索供应商时
    searchSupplierChange: function (events) {
        var keywords = events.detail.value.trim();

        this.setData({
            [`formData.supply_id`]: keywords,
            [`sel_text.supply_text`]: keywords,
            supplier_keywords: keywords,
            supplier_list: [],
            supplier_now_page: 0,
            supplier_total: 0,
        });
        this.get_supplier_list(1);
    },
    open_bom_select(e) {
        this.setData({
            is_show_choose_pro: true,
            is_shade_screen: true,
            bom_index: e.currentTarget.dataset.index,
            bom_index2: e.currentTarget.dataset.index2,
        })
    },

    // 搜索供应商时
    searchBomChange: function (events) {
        var keywords = events.detail.value.trim();
        let materials = this.data.materials;
        let bom_index = this.data.bom_index
        let bom_index2 = this.data.bom_index2
        materials[bom_index].sku_list[bom_index2].bom_id = { name: keywords };
        this.setData({
            materials,
        });
    },

    // 选择物料
    ChooseWuliao: function (events) {
        var __this = this;
        // 验证是否选择供应商
        if (__this.data.formData.supply_id == 0) {
            wx.showToast({
                title: '请先选择供应商',
                icon: 'none',
                duration: 1500,
            });
            return false;
        }
        // 打开选择颜色页面
        wx.navigateTo({
            url: '/pages/choose_wuliao/choose_wuliao',
            events: {
                // 当选择完成时
                changeData: function (data) {
                    __this.setData({
                        bom_list: data
                    });
                }
            },
            success: function (res) {
                // 向被打开页面传送数据
                res.eventChannel.emit('acceptDataFromOpenerPage', {
                    bom_list: __this.data.bom_list,
                    supply_id: __this.data.formData.supply_id
                });
            }
        });
    },

    // 当输入时
    selFormInputChange: function (e) {
        var index = e.currentTarget.dataset.index;
        var field = e.currentTarget.dataset.field;
        this.data.bom_list[index][field] = e.detail.value.trim();
        this.setData({
            bom_list: this.data.bom_list
        });
    },
    deleteImage(e) {
        let { index } = e.currentTarget.dataset
        let index2 = e.detail.index
        let materials = this.data.materials
        materials[index].fileList.splice(index2, 1);
        this.setData({
            materials
        })
    },
    // 选择交期时
    bindDeadLineChange: function (e) {
        var index = e.currentTarget.dataset.index;
        var field = e.currentTarget.dataset.field;
        this.data.bom_list[index][field] = e.detail.value;
        this.setData({
            bom_list: this.data.bom_list
        })
    },

    // 取消选择
    chooseDel: function (e) {
        var index = e.currentTarget.dataset.index;
        var index2 = e.currentTarget.dataset.index2;
        var materials = this.data.materials
        materials[index].sku_list.splice(index2, 1);
        // 重置data
        this.setData({
            materials,
        });
    },

    // 提交
    formSubmit: function (e) {
        console.log(this.data.purchase_id)
        if (this.data.purchase_id > 0) {
            return false;
        }
        console.log('提交')
        var __this = this;


        var req_arr = [];
        var substring = 'babiboy'
        this.data.materials.forEach((element, index) => {
            var fileList = element.fileList
            if (element.fileList !== undefined) {
                fileList.forEach(function (v, k) {
              
                    if (v.tempFilePath !== undefined && !v.tempFilePath.includes(substring)) {
                        var result = app.request_upload('', {
                            cdn_url: __this.data.web_data.siteConfig.apiUrl,
                            token: __this.data.web_data.siteConfig.upload.token,
                            is_old_file: 0
                        }, v.tempFilePath, k, false);
                        req_arr.push(result);
                        // 处理结果
                        result.then(res => {
                            console.log('sc', res)
                            let insert_data = {
                                "url": res.file_path,
                                "thumb": res.file_path,
                                "fileType": "image",
                                "value": res.file_key
                            }
                            __this.data.materials[index].fileList[res.for_i] = insert_data;
                            __this.setData({
                                materials: __this.data.materials
                            });
                        });
                    }
                    if (v.thumb !== undefined && !v.thumb.includes(substring)) {
                        var result = app.request_upload('', {
                            cdn_url: __this.data.web_data.siteConfig.apiUrl,
                            token: __this.data.web_data.siteConfig.upload.token,
                            is_old_file: 0
                        }, v.thumb, k, false);
                        req_arr.push(result);
                        // 处理结果
                        result.then(res => {
                            console.log('sc', res)
                            let insert_data = {
                                "url": res.file_path,
                                "thumb": res.file_path,
                                "fileType": "image",
                                "value": res.file_key
                            }
                            __this.data.materials[index].fileList[res.for_i] = insert_data;
                            __this.setData({
                                materials: __this.data.materials
                            });
                        });
                    }

                })
            }


            var fileList2 = element.fileList2
            if (element.fileList2 !== undefined) {
                fileList2.forEach(function (v, k) {
                    if (v.tempFilePath !== undefined &&  !v.tempFilePath.includes(substring)) {
                        var result = app.request_upload('', {
                            cdn_url: __this.data.web_data.siteConfig.apiUrl,
                            token: __this.data.web_data.siteConfig.upload.token,
                            is_old_file: 0
                        },  v.tempFilePath, k, false);
                        req_arr.push(result);
                        // 处理结果
                        result.then(res => {
                            console.log('sc', res)
                            let insert_data = {
                                "url": res.file_path,
                                "thumb": res.file_path,
                                "fileType": "image",
                                "value": res.file_key
                            }
                            __this.data.materials[index].fileList2[res.for_i] = insert_data;
                            __this.setData({
                                materials: __this.data.materials
                            });
                        });
                    }
                    if ( v.thumb !== undefined  &&  !v.thumb.includes(substring)) {
                      
                        var result = app.request_upload('', {
                            cdn_url: __this.data.web_data.siteConfig.apiUrl,
                            token: __this.data.web_data.siteConfig.upload.token,
                            is_old_file: 0
                        }, v.thumb, k, false);
                        req_arr.push(result);
                        // 处理结果
                        result.then(res => {
                            console.log('sc', res)
                            let insert_data = {
                                "url": res.file_path,
                                "thumb": res.file_path,
                                "fileType": "image",
                                "value": res.file_key
                            }
                            __this.data.materials[index].fileList2[res.for_i] = insert_data;
                            __this.setData({
                                materials: __this.data.materials
                            });
                        });
                    }

                })
            }

        });

        // 全部上传成功后调用
        Promise.all(req_arr).then(res => {
            var req_param = __this.data.formData;
            req_param.category_ids = __this.data.choose_cate_id_arr;
            req_param.time_category_ids = __this.data.choose_style_id_arr;

            req_param.bom_list = __this.data.materials;
            var result = app.request_api('admin/purchase/mini_add', req_param, true);
            result.then(res => {
                // 向上一级页面传递参数
                // var eventChannel = __this.getOpenerEventChannel();
                // eventChannel.emit('changeData', {});
                // console.log('aaa成功')
                // 跳转回前一页
                wx.showModal({
                    title: '提示',
                    content: '提交成功',
                    showCancel: false,
                    complete() {
                        wx.navigateTo({
                            url: '/pages/purchase_list/purchase_list',
                        })
                        // wx.navigateBack(2);
                    }
                });
            });
        }).catch(error => {
            console.log(error);
            wx.hideLoading();
        });
        console.log('完成2')
        return;

    },
    selectUnit: function (events) {
        var __this = this;
        let { index } = events.currentTarget.dataset
        // 打开选择颜色页面
        wx.navigateTo({
            url: '/pages/choose_unit/choose_unit',
            events: {
                // 当选择完成时
                changeData: function (data) {
                    var materials = __this.data.materials
                    const unit = `materials[${index}].unit`;
                    const check_unit = `materials[${index}].check_unit`;
                    const unit_rate = `materials[${index}].unit_rate`;
                    const check_price = `materials[${index}].check_price`;
                    __this.setData({
                        [unit]: data.cgunit,
                        [check_unit]: data.hlunit,
                        [unit_rate]: data.unitrate,
                        "selectUnit": data,
                        [check_price]: materials[index].price * data.unitrate
                    });
                }
            },
            success: function (res) {
                // 向被打开页面传送数据
                let params = {};
                params.dataset = 'a';
                res.eventChannel.emit('acceptDataFromOpenerPage', {
                    sel_list: __this.data.selectUnit || {}
                });
            }
        });
    },
    // 修改时的提交
    formSubmitUpdate: function (e) {
        if (this.data.purchase_id == 0) {
            return false;
        }
        // 组装参数
        var __this = this;
        var req_param = __this.data.formData;
        req_param.bom_list = __this.data.bom_list;
        req_param.purchase_id = __this.data.purchase_id;
        // 发起请求
        var result = app.request_api('admin/purchase/edit', req_param, true);
        result.then(res => {
            // 向上一级页面传递参数
            var eventChannel = __this.getOpenerEventChannel();
            eventChannel.emit('changeData', {});
            // 跳转回前一页
            wx.showModal({
                title: '提示',
                content: '保存成功',
                showCancel: false,
                complete() {
                    wx.navigateBack();
                }
            });
        });
    },

    // 请求数据
    get_data_all: function () {
        var __this = this;
        var req_arr = [];
        // 组装请求
        if (this.data.purchase_id > 0) {
            // 获取详情
            var detail_res = this.get_row_data();
            req_arr.push(detail_res);
        }
        // 获取采购员
        var buyer_res = this.get_buyer_list();
        var get_MaterialCategory_list = this.get_MaterialCategory_list();

        req_arr.push(get_MaterialCategory_list);
        req_arr.push(buyer_res);
        // 获取供应商
        var supplier_res = this.get_supplier_list();
        req_arr.push(supplier_res);
        // 全部完成
        Promise.all(req_arr).then(res => {
            if (__this.data.purchase_id > 0) {
                // 采购员
                var buyer_text = '';
                var buyer_index = __this.data.buyer_list.findIndex(obj => obj.id === __this.data.formData.buyer_id);
                if (buyer_index > -1) {
                    buyer_text = __this.data.buyer_list[buyer_index].realname;
                }
                __this.setData({
                    [`sel_text.buyer_text`]: buyer_text,
                });
                // 重新请求供应商
                if (__this.data.formData.supply_id > 0) {
                    __this.setData({
                        supplier_list: [],
                        supplier_total: 0,
                        supplier_now_page: 0,
                        supplier_keywords: __this.data.formData.supply_id
                    });
                    var supplier_res2 = this.get_supplier_list();
                    supplier_res2.then(res2 => {

                        if (res2.list.length > 0) {
                            var supplier_index = res2.list.findIndex(obj => obj.id === __this.data.formData.supply_id);
                            if (supplier_index > -1) {
                                __this.setData({
                                    [`sel_text.supply_text`]: res2.list[supplier_index].SupplyNa,
                                });
                            }
                        }
                    });
                }
            }
        }).catch(error => {
            console.log(error);
        });
    },

    // 获取详情
    get_row_data: function () {
        var result = app.request_api('admin/Purchase/edit', {
            purchase_id: this.data.purchase_id
        }, true, 'GET');
        result.then(res => {
            var type_index = this.data.type_list.findIndex(obj => obj.id === res.row.type);
            var type_text = '';
            if (type_index > -1) {
                type_text = this.data.type_list[type_index].name
            }
            this.setData({
                edit_data: res.row,
                [`formData.purchase_time`]: res.row.purchase_time,
                [`formData.purchase_name`]: res.row.purchase_name,
                [`formData.first_order`]: res.row.first_order,
                [`formData.buyer_id`]: res.row.buyer_id,
                [`formData.type`]: res.row.type,
                [`formData.supply_id`]: res.row.supply_id,
                [`formData.sg_purchase_sn`]: res.row.purchase_sn,
                [`sel_text.type_text`]: type_text,
                bom_list: res.row.bom_list
            });
        });
        // 返回
        return result;
    },


})